package com.example.zjx8969.myapplication.inject;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;

public class DynamicHandler implements InvocationHandler {
    private WeakReference<Object> handlerRef;
    private final HashMap<String, Method> methodMap = new HashMap<>(
            2);

    public DynamicHandler(Object activity) {
        this.handlerRef = new WeakReference<>(activity);
    }

    public void addMethod(String name, Method method) {
        methodMap.put(name, method);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object o = handlerRef.get();
        if (o == null) return null;
        method = methodMap.get(method.getName());
        if (method != null) {
            return method.invoke(o, args);
        }
        return null;
    }
}
